<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" shadow>
      <!-- 头部功能 -->
      <template #header>
        <div>
          <el-button type="primary" @click="showAddSortPage()"
            >添加分类</el-button
          >
        </div>
      </template>
      <!-- 正文内容 -->
      <ZkTable
        v-loading="loading"
        :data="sorts"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
      >
        <template #state="{ row }">
          <i
            class="tip"
            :class="row.cat_deleted ? 'el-icon-error' : 'el-icon-success'"
          ></i>
        </template>
        <template #level="{ row }">
          <el-tag v-show="row.cat_level == 0" size="mini"> 一级 </el-tag>
          <!-- effect="dark" -->
          <el-tag v-show="row.cat_level == 1" size="mini" type="success">
            二级
          </el-tag>
          <el-tag v-show="row.cat_level == 2" size="mini" type="warning">
            三级
          </el-tag>
        </template>
        <template #btn="{ row }">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            class="updateRole"
            @click="updateSortData(row)"
            >编辑</el-button
          >

          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removeSortrById(row.cat_id)"
            >删除</el-button
          >
        </template>
      </ZkTable>
      <el-dialog title="修改分类" :visible.sync="updateRoleVisible">
        <el-form :model="sort" ref="updateRolesForm" :rules="$rules.good">
          <el-form-item
            prop="cat_name"
            label="分类名称"
            :label-width="formLabelWidth"
          >
            <el-input v-model="sort.cat_name"> </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="updateRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="modifySortById()">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分页器 -->
      <el-pagination
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        @size-change="reloadUserlistSize"
        @current-change="reloadUserlistPage"
        :current-page="pagenum"
      >
      </el-pagination>
    </el-card>
    <el-dialog title="分类添加" :visible.sync="addSortVisible">
      <el-form :model="sort" ref="addSortForm" :rules="$rules.good">
        <el-form-item
          prop="cat_name"
          label="分类名称"
          :label-width="formLabelWidth"
        >
          <el-input v-model="sort.cat_name" placeholder="请输入新分类名称">
          </el-input>
        </el-form-item>
        <el-form-item label="父级分类" :label-width="formLabelWidth">
          <el-cascader
            placeholder="不选择添加主分类"
            :options="options"
            :props="{
              checkStrictly: true,
              label: 'cat_name',
              value: 'cat_id',
            }"
            clearable
            v-model="newSortArr"
            @change="setNewSortArr"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addSortVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSortList()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import ZkTable from "vue-table-with-tree-grid";
export default {
  components: { ZkTable },
  data() {
    return {
      columns: [
        { label: "分类名称", prop: "cat_name" },
        { label: "是否有效", type: "template", template: "state" },
        { label: "等级", type: "template", template: "level" },
        { label: "操作", type: "template", template: "btn" },
      ],
      sorts: [],
      sort: {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0,
      },
      newSortArr: [],
      options: [],
      addSortVisible: false,
      updateRoleVisible: false,
      formLabelWidth: "100px",
      loading: false,
      total: 16, //总页数
      pagesize: 5, //页面数据调
      pagenum: 1, //当前页码
      query: "", //加载页面条件限制参数
    };
  },
  methods: {
    //刷新页面数据(传pagenum和pagesize)
    async initSortsList() {
      try {
        this.loading = true;
        let sorts = await this.$api.getSortsList({
          query: this.query,
          pagenum: this.pagenum,
          pagesize: this.pagesize,
        });
        if (sorts == "error") return;
        this.sorts = sorts.result;
        this.total = sorts.total;
        this.pagenum = sorts.pagenum + 1; // 这行代码可以定义也可以不定义，主要为保证和后端服务器结果同步
        // this.options.label=this.options.cat_name
        console.log("初始化数据222222", sorts);
      } catch (error) {
        console.log("RoleView-initSortsList-error:", error);
      } finally {
        this.loading = false;
      }
    },
    //拿到页面所有数据(不传pagenum和pagesize,传type)
    async initAllSortsList() {
      try {
        this.loading = true;
        let sorts = await this.$api.getSortsList({
          type: 2,
        });
        if (sorts == "error") return;
        this.options = sorts;
        // this.options.label=this.options.cat_name
        console.log("初始化数据333", sorts);
      } catch (error) {
        console.log("RoleView-initSortsList-error:", error);
      } finally {
        this.loading = false;
      }
    },
    //级联选择器返回的内容是数组
    setNewSortArr() {
      console.log("setNewSortArr", this.newSortArr);
      let leg = this.newSortArr.length;
      if (leg == 0) {
        this.sort.cat_level = 0;
        this.sort.cat_pid = 0;
      } else {
        this.sort.cat_level = leg; //级别
        this.sort.cat_pid = this.newSortArr[leg - 1];
      }
      console.log("1qwqw", this.sort, leg);
    },

    //添加页面的展示和页面的清空
    showAddSortPage() {
      this.initAllSortsList();
      this.sort = {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0,
      };
      this.newSortArr = [];
      this.addSortVisible = true;
    },
    //添加分类
    async addSortList() {
      try {
        await this.$refs.addSortForm.validate(); //对$rolesForm(该表单的输入值)进行校验
        let params = {
          cat_name: this.sort.cat_name,
          cat_pid: this.sort.cat_pid,
          cat_level: this.sort.cat_level,
        };
        let data = await this.$api.addSortsList(params);
        this.addSortVisible = false;
        console.log("添加分类111", data, 11121332, this.sort, 333, params);
        if (data == "error") return;
        this.$message.success("添加成功");
        this.initSortsList();
      } catch (error) {
        console.log("RoleView-addSortList-error:", error);
      }
    },
    //编辑分类信息
    async modifySortById() {
      try {
        console.log(11222, this.sort);
        let data = await this.$api.updateSortsList(this.sort.cat_pid, {
          cat_name: this.sort.cat_name,
        });
        console.log(12345, data);
        if (data == "error") return;
        this.$message.success("编辑成功");
        this.updateRoleVisible = false;
        this.initSortsList();
      } catch (error) {
        console.log("UserView-modifyUserById-error:", error);
      }
      console.log(11);
    },
    //拿到当前点击的按钮分类名称
    updateSortData(sort) {
      this.sort = {
        cat_pid: sort.cat_id,
        cat_name: sort.cat_name,
        cat_level: sort.cat_pid,
      };
      console.log("sort", sort);
      this.updateRoleVisible = true;
    },
    //删除角色信息
    async removeSortrById(id) {
      try {
        let data = this.$api.deleteSortsList(id);
        // console.log(22, data);
        if (data == "error") return;
        this.$message.success("删除成功");

        //当删除的数据是最后一页的最后一条数据时，必须将pagenum-1，否则页面会显示pagenum的数据，处于无数据状态
        let lastFlag = this.total % this.pagesize == 1; //判断最后的页面是不是只有一条数据
        let lastPageFlag =
          Math.ceil(this.total / this.pagesize) == this.pagenum; //判断当前是否处于最后一页
        if (lastFlag && lastPageFlag && this.pagenum != 1) {
          this.pagenum = this.pagenum - 1;
        }

        this.initSortsList();
      } catch (error) {
        console.log("RoleView-removeSortrById-error:", error);
      }
    },
    reloadUserlistSize(newPagePage) {
      // console.log(this.pagenum,newPagePage);
      this.pagesize = newPagePage;
      this.initSortsList();
    },
    //pageSize改变时触发(每一页)
    reloadUserlistPage(newPageNum) {
      // console.log(this.pagenum, newPageNum);
      this.pagenum = newPageNum;
      this.initSortsList();
    },
  },
  created() {
    this.initSortsList();
  },
};
</script>

 <style lang="less" scoped>
.el-button {
  margin: 0;
}
.el-button,
.updateRoles {
  margin-right: 10px;
}
.tip {
  font-size: 18px;
  color: #67c23a;
}

.el-cascader {
  width: 100%;
}
</style>